// pages/intellect/index.js
//引入插件：微信同声传译
const plugin = requirePlugin('WechatSI');
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();
import {language} from'../../utils/conflg'
import {getchatgpt,getAccessToken} from"../../api/https"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    items: [
      {value: '文心一言'},
      {value: 'ChatGPT', checked: 'true'},
      {value: '科技星火'},
      {value: '盘古'},
      {value: '一通千问'},
    ],
    robotName:'文心一言',
    list:[],
    usertxt:'',
    inner:null,
    scroll_top:1000,
    dian:'',
    myflag:false,
    flag:true,
    newflag:false,
    toView:'fake',
    num:null,
    is_clock:false,
    startPoint:0,
    show: false,
    duration: 300,
    position: 'top',
    round: true,
    overlay: true, 
    customStyle: '',
    overlayStyle: ''
  },
    // 2024------新增智能产品------
    clickckout(e){
      const position = e.currentTarget.dataset.position
      let customStyle = ''
      let duration = this.data.duration
      switch(position) {
        case 'top': 
          customStyle = 'height: 20%;'
          break
      }
      this.setData({
        position,
        show: true,
        customStyle,
        duration
      })
    },

    // 切换模型
    radioChange(e){
      console.log(e.detail.value)
      this.setData({
        robotName:e.detail.value
      })
      switch(e.detail.value){
        case '文心一言':
        
        break;

        case 'ChatGPT':
        
        break;

        case '科技星火':
        
        break;

        case '盘古':
        
        break;

        case '一通千问':
        
        break;
      }
    },


  //页面初始化   
  onLoad(){let inner=wx.createInnerAudioContext();this.initRecord();this.setData({inner,toView:this.data.toView})},

  /**
   * 重新滚动到底部
   */
  scrollToNew: function() {
    this.setData({
      toView: this.data.toView
    })
  },
  getflagnum(e){
    let {inner}=this.data
    inner.pause()
    wx.showToast({
        title:'播放暂停',
        icon: 'none',
      }); 
    this.setData({
        myflag:this.data.myflag
    })
  },
// 语音播放  
  getpath(e){
          let {inner,list}=this.data
          if(e.detail.num==0){
            inner.src=e.detail.tempFilePath;
            inner.autoplay=true
            inner.onPlay(()=>{})
            inner.onError((res)=>{
              console.log(res.errMsg)
            })
          }else{
            inner.stop() 
            list[e.detail.flagnum].flag=false
            this.setData({
              list:list,
            })
          }
          inner.onEnded(()=>{
            list[e.detail.flagnum].flag=false
            this.setData({
              list:list,
            })
          }) 
  },
// 清除所有内容
  inclick(){
    let than=this;
    wx.showModal({
      title: '是否要清屏？',
      content: '',
      success (res) {
        if (res.confirm) {
          wx.setStorageSync('list',JSON.stringify([]))
          than.setData({
            list:[]
          })
          onLoad();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

swtchtype(e){
  this.setData({
    flag:!e.currentTarget.dataset.flag
  })
},
//发语音
yuyin(e){
  console.log(e)
  this.setData({
    newflag:true,
    is_clock:true,//长按时应设置为true，为可发送状态
    startPoint:e.touches[0],//记录触摸点的坐标信息
  })
  manager.start({lang:'zh_CN',})
},

// 手松开
skai(e){
  manager.stop()
  let {startPoint}=this.data
  //计算距离，当滑动的垂直距离大于25时，则取消发送语音
  if (Math.abs((e.changedTouches[e.changedTouches.length-1].clientY)-(startPoint.clientY))>25){
    wx.showToast({
      title: '已取消',
    })
        this.setData({
          is_clock: false,//设置为不发送语音
          newflag:false
        })
        return
  }
  this.setData({
    is_clock:true,//设置为不发送语音
    newflag:false
  })

},

initRecord: function() {
    //有新的识别内容返回，则会调用此事件
    manager.onRecognize = (res) => {
      this.scrollToNew();
    }

    // 识别结束事件
    manager.onStop = (res) => {
      let {list,inner,is_clock}=this.data;
      let text = res.result
      if(is_clock==false){
        return
      }

      if(text == '') {  
        wx.showToast({
          title: '没听清楚你说的是什么？',
          icon:'error',
          duration:1000
        })
        return
      }


      let obj={'user':text,'flag':false}
      list.push(obj)
        this.setData({
          list:list,
        })
      this.scrollToNew();
      this.setdian()
      let than=this;
      getchatgpt(text).then(res=>{
        if(res.data!==''){
          obj.gpt=res.data;
          than.setData({
            list:list,
            myflag:true,
          })
          wx.setStorageSync('list',JSON.stringify(list))
          plugin.textToSpeech({
              lang:'zh_CN',
              content:res.data,
              success(res){
                 than.setdian(false)
                 this.scrollToNew();
                  inner.src=res.filename
                  inner.autoplay=true;
                  inner.onPlay(res=>{})
                  inner.onError(err=>{
                      wx.showToast({
                        title: '暂时无法语音为你播放,你可以点击我的头像试试。',
                      }) 
                  })
                  inner.onEnded(res=>{})
              },
              fail(err){
                console.log(err)
              }
              
          })
        }
      })
    }
    // 识别错误事件
    manager.onError = (res) => {


    }
},

  newpath(text){
    
  },

// 反复触发
  onShow(){
    this.scrollToNew();
    wx.showToast({
      title: `切换到Ai模式`,
      icon: 'none',
    });
    let list=wx.getStorageSync('list')
  
    if(list){
      this.setData({
        list:JSON.parse(list)
      })
    }
    this.setData({
        toView:this.data.toView 
    })
  },   
// 加载动画
  setdian(bool=true){
    let than=this;
    let temr=null;
    clearInterval(temr)
    let {dian}=this.data
    if(bool){
      temr=setInterval(()=>{
        dian+='.'
        if(dian.length>6){
          dian=''
        }
        than.setData({
          dian
        })
      },1000)
    }else{
      clearInterval(temr)
    }
  },
//点击发送
  userclick(){
    this.setdian()
    let {usertxt,list}=this.data;
    if(usertxt==''||!usertxt.trim(usertxt)){
      wx.showToast({
        title: '请输入内容！',
        icon:'error',
        duration:2000
      })
      this.setData({
        usertxt:'',
      })
      return
    }
    let obj={'user':usertxt,'flag':false}
    list.push(obj)
      this.setData({
        list:list,
        usertxt:'',
      })
      this.scrollToNew();
    let than=this;
    getchatgpt(usertxt).then(res=>{
      if(res.data!==''){
        than.setdian(false)
        obj.gpt=res.data;
        than.setData({
          list:list,
          toView:`item${list.length - 1}`
        })
        wx.setStorageSync('list',JSON.stringify(list))
      }
    })
  },
// 删除内容
  resevmo(e){
    let {list}=this.data
    let than=this
    wx.showModal({
      title: list[e.currentTarget.dataset.index].user,
      content: '你确定要删除吗？',
      success (res) {
        if (res.confirm) {
          list.splice(e.currentTarget.dataset.index,1)//删除元素
          than.setData({
            list:list
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 文字输入
  userput(e){
    this.setData({
      usertxt:e.detail.value
    })
  },
})